package com.easybuilder.blog.service.impl;

import com.easybuilder.blog.dao.BlogReplyDao;
import com.easybuilder.blog.dto.BlogReplyDTO;
import com.easybuilder.blog.entity.BlogReply;
import com.easybuilder.blog.service.ReplyService;
import com.easybuilder.common.utils.TimeUtil;
import com.easybuilder.common.utils.UserUtil;
import com.easybuilder.core.rbac.entity.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {

    @Resource
    private BlogReplyDao replyDao;

    /** 发表回复 */
    @Override
    public BlogReply publish(BlogReply reply) {
        SysUser user = UserUtil.getUser();
        // 设置回复人相关信息
        if (user != null) {
            reply.setFromId(user.getId());
            reply.setFromNickname(user.getNickname());
            reply.setFromImg(user.getImg());
        }
        reply.setCreateTime(new Date());
        replyDao.insertSelective(reply);
        return reply;
    }

    /** 根据回复类型和回复对象id获取回复列表
     * @return*/
    @Override
    public List<BlogReplyDTO> selectByTypeAndReplyId(int type, Long replyId) {
        List<BlogReply> blogreplys = replyDao.selectByTypeAndReplyId(type, replyId);
        List<BlogReplyDTO> result = new ArrayList<>();
        if (blogreplys != null && blogreplys.size() > 0) {
            for (BlogReply blogreply : blogreplys) {
                BlogReplyDTO replyDTO = new BlogReplyDTO();
                BeanUtils.copyProperties(blogreply, replyDTO);
                // 递归设置当前回复的子回复数据
                recursionSetreply(replyDTO);
                result.add(replyDTO);
            }
        }
        return result;
    }


    /** 统计回复量 */
    @Override
    public List<Integer> countReply() {
        return replyDao.countReply(TimeUtil.getFormatDay(new Date()));
    }

    public void recursionSetreply(BlogReplyDTO replyDTO){
        List<BlogReply> blogreplys = replyDao.selectByTypeAndReplyId(1, replyDTO.getId());
        List<BlogReplyDTO> result = new ArrayList<>();
        if (blogreplys != null && blogreplys.size() > 0) {
            for (BlogReply blogreply : blogreplys) {
                BlogReplyDTO childreplyDTO = new BlogReplyDTO();
                BeanUtils.copyProperties(blogreply, childreplyDTO);
                // 递归设置当前回复的子回复数据
                recursionSetreply(childreplyDTO);
                result.add(childreplyDTO);
            }
            replyDTO.setReplyCount(blogreplys.size());
            replyDTO.setReplyList(result);
        } else {
            replyDTO.setReplyCount(0);
        }
    }
}
